<template>
  <!-- 提交订单信息 -->
  <div class="submitOrder">
    <!-- 顶部导航栏 -->
    <div class="header">
      <van-sticky>
        <van-nav-bar
          title="确定订单"
          left-text="返回"
          left-arrow
          @click-left="BtnBack"
        />
      </van-sticky>
    </div>
    <!-- 内容 -->
    <div class="content">
      <div class="address" @click="show = true">
        <van-cell-group>
          <van-cell title="服务地址" icon="location-o" />
          <div style="padding: 5px 34px" class="info">
            <span
              >姓名：<label>{{ addressItem.username }}</label></span
            >
            <span
              >电话：<label>{{ addressItem.telephone }}</label></span
            >
          </div>
          <div style="padding: 4px 34px; font-size: 15px">
            <span>地址：</span>
            <span style="color: #666">{{ addressItem.addressInfo }}</span>
          </div>
        </van-cell-group>
      </div>

      <van-action-sheet v-model="show" title="选择地址">
        <div class="content">
          <van-radio-group v-model="radio">
            <van-radio
              v-for="(item, index) in allAddressData"
              :key="index"
              :name="index"
              checked-color="#ee0a24"
              @click="radioClick"
            >
              <div class="AddressInfo">
                <div style="padding: 2px 10px; font-size: 15px" class="info">
                  <span
                    >姓名：<label style="color: #666">{{
                      item.username
                    }}</label></span
                  >
                  <span
                    >电话：<label style="color: #666">{{
                      item.telephone
                    }}</label></span
                  >
                </div>
                <div style="padding: 2px 10px; font-size: 15px">
                  <span>地址：</span>
                  <span style="color: #666">{{
                    item.province + item.city + item.area + item.address
                  }}</span>
                </div>
              </div>
            </van-radio>
          </van-radio-group>
        </div>
      </van-action-sheet>

      <!-- 订单详情 -->
      <div class="ProductInfo">
        <van-cell-group>
          <van-cell title="订单详情" icon="orders-o" />
          <div
            style="padding: 2px 4px 2px 34px"
            class="product"
            v-for="(product, index) in productInfo"
            :key="index"
          >
            <span>{{ product.productName }}</span>
            <span
              >价格：<label>￥{{ product.price }}</label></span
            >
            <span
              >数量：<label>x{{ product.number }}</label></span
            >
          </div>
          <div class="total">
            总价：<label style="color: red; font-size: 15px"
              >￥{{ total }}</label
            >
          </div>
        </van-cell-group>
      </div>

      <!-- 选择服务时间 -->
      <div class="serviceTime" @click="showTime = true">
        <van-cell title="服务时间" icon="clock-o" :value="time" />
      </div>
    </div>

    <van-action-sheet v-model="showTime">
      <!-- <div class="time"> -->
        <van-datetime-picker
          v-model="currentDate"
          type="datetime"
          :columns-order="['year', 'month', 'day', 'hour', 'minute']"
          :min-date="minDate"
          :max-date="maxDate"
          @cancel="onCancel"
          @confirm="onConfirm"
          :formatter="formatter"
        />
      <!-- </div> -->
    </van-action-sheet>

    <!-- 提交订单按钮 -->
    <div class="btnSubmit" @click="btnSubmit">确定提交</div>

    <!-- 充值余额 -->
    <van-action-sheet title="充值" v-model="showRecharge" @close="close">
      <div class="money">
        <span>充值金额</span>
        <input type="text" v-model="payMoney" placeholder="请输入充值金额" />
      </div>
      <div class="submit">
        <button @click="Pay()">提交</button>
      </div>
    </van-action-sheet>
  </div>
</template>

<script>
// 引入axios
import { get, post, post_json } from "@/http/axios";
import { mapState, mapGetters, mapMutations } from "vuex";
import { Notify, Dialog } from "vant";
export default {
  data() {
    return {
      // 时间选择
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(),
      //时间戳
      timeStamp: "",
      //
      time: "",
      //单选按钮
      radio: "",
      //
      showRecharge: false,
      //
      show: false,
      //时间
      showTime: false,
      fieldValue: "",
      cascaderValue: "",
      //地址数据
      allAddressData: [],

      //产品详情数据
      productInfo: [],
      //
      addressItem: {
        id: "",
        //姓名
        username: "",
        //电话
        telephone: "",
        //收获地址
        addressInfo: "",
        
      },
      //用户信息
        userInfo: {},
      //充值额度
      payMoney: "",
    };
  },
  methods: {
    //时间 类型 年月日 时分秒
    formatter(type, val) {
      if (type === "year") {
        return val + "年";
      }
      if (type === "month") {
        return val + "月";
      }
      if (type === "day") {
        return val + "日";
      }
      if (type === "hour") {
        return val + "时";
      }
      if (type === "minute") {
        return val + "分";
      }

      return val;
    },
    // 引入shopcart  vuex中的方法
    ...mapMutations("shopcart", ["clearShopcart"]),

    //标准时间转换为年月日 时分秒 格式
    formatTen(num) {
      return num > 9 ? num + "" : "0" + num;
    },
    formatDate(val) {
      // console.log(this.currentDate);
      if (val == null) {
        var date = new Date(this.currentDate);
      } else {
        var date = new Date(val);
      }

      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var hour = date.getHours();
      var minute = date.getMinutes();
      var second = date.getSeconds();
      this.time =
        year +
        "-" +
        this.formatTen(month) +
        "-" +
        this.formatTen(day) +
        " " +
        this.formatTen(hour) +
        ":" +
        this.formatTen(minute) +
        ":" +
        this.formatTen(second);

      console.log(this.time);
    },
    //确定按钮  服务时间
    onConfirm(val) {
      //关闭那个底部弹出 框
      this.showTime = false;
      // console.log(val);
      //调用 该方法 转为时间戳
      this.formatDate(val);
    },

    //确定充值按钮
    async Pay() {
      let data = {
        customerId: this.userInfo.id,
        money: this.payMoney,
      };
      let res = await get("/account/recharge", data);
      // console.log(res);
      // 给用户一个成功或失败的提示
      if (res.data.status == 200) {
        Notify({ type: "success", message: res.data.message, duration: 1500 });
        this.showRecharge = false;
      } else if (res.data.status == 500) {
        console.log(this.userInfo.id);
        if (res.data.message == "一次最多只能充值1000元！") {
          Notify({
            type: "warning",
            message: res.data.message,
            duration: 1500,
          });
        } else if (this.userInfo.id != null) {
          Notify({
            type: "warning",
            message: "充值金额输入不规范！",
            duration: 1500,
          });
        } else {
          Notify({
            type: "danger",
            message: res.data.message,
            duration: 1500,
          });
        }
      } else {
        Notify({ type: "danger", message: res.data.message, duration: 1500 });
      }
    },

    //关闭充值面板 按钮后  清空输入的充值金额
    close() {
      // console.log(1);
      this.payMoney = "";
    },

    //取消按钮
    onCancel() {
      this.showTime = false;
    },
    //确定提交按钮
    async btnSubmit() {
      // console.log(this.payMoney);
      // console.log(1);
      var date = new Date(this.time);

      // console.log(userInfo.data.data.id);

      //产品信息
      let orderLine = [];
      this.productInfo.forEach((item) => {
        // console.log(item);
        let params = {
          id: 0,
          number: item.number,
          orderId: 0,
          price: item.price,
          productId: item.productId,
        };
        orderLine.push(params);
      });
      // console.log(orderLine);
      if (orderLine == "") {
        Notify({
          type: "warning",
          message: "订单详情不能为空！",
          duration: 1500,
        });
        return;
      }else if (this.addressItem.id == "") {
        Notify({
          type: "warning",
          message: "收获地址不能为空！",
          duration: 1500,
        });
        return;
      }

      let data = {
        addressId: this.addressItem.id,
        customerId: this.userInfo.id,
        orderLines: orderLine,
        serviceTime: date.getTime(),
      };
      // console.log(JSON.stringify(data));
      let res = await post_json("/order/submitOrder", JSON.stringify(data));
      // console.log(res);
      if (res.data.status == 200) {
        this.$router.push({
          path: "/manager/order",
        });
        Notify({ type: "success", message: "提交成功" });
        //清空购物车
        this.clearShopcart();
        this.productInfo = [];
        // console.log(this.productInfo);
      } else if (res.data.message == "余额不足!") {
        Dialog.confirm({
          title: "当前余额不足，是否充值?",
        })
          .then(() => {
            // on confirm
            this.showRecharge = true;
          })
          .catch(() => {
            // on cancel
          });
      } else {
        Notify({ type: "danger", message: res.data.message });
      }
    },
    // onSelect(item) {
    //   // console.log(item);
    //   this.show = false;
    //   this.$toast({
    //     message: item.name,
    //     duration: 500,
    //   });
    // },

    
    //单选按钮
    radioClick() {
      //   console.log(this.radio);
      this.getAddressItem(this.radio);
      this.show = false;
    },
    //返回按钮
    BtnBack() {
      this.$router.go(-1);
    },

    //
    onFinish() {
      this.show = false;
      this.fieldValue = selectedOptions.map((option) => option.text).join("/");
    },

    //获取地址
    async getAllAddress() {
     
      //获取用户信息
      let info = await get("/user/info?token=" + localStorage.getItem("token"));
      this.userInfo = info.data.data;
      console.log(this.userInfo.id);
      let data = {
        page: 1,
        pageSize: 100,
        userId:this.userInfo.id,
      };
      let res = await get("/address/pageQuery", data);
      this.allAddressData = res.data.data.list;
      this.getAddressItem(0);
    },
    //
    getAddressItem(item) {
      
      if(!this.allAddressData[item].id){
        this.addressItem.id = '';

      this.addressItem.username = '';
      this.addressItem.telephone = '';
      this.addressItem.addressInfo = '';
      return;
      }

      this.addressItem.id = this.allAddressData[item].id;

      this.addressItem.username = this.allAddressData[item].username;
      this.addressItem.telephone = this.allAddressData[item].telephone;
      this.addressItem.addressInfo =
        this.allAddressData[item].province +
        this.allAddressData[item].city +
        this.allAddressData[item].area +
        this.allAddressData[item].address;

      //   console.log(this.addressItem);
    },

    //过滤 数量为0的产品
    //过滤数量为0的购物车
    filtersProductData() {
      this.orderLines.forEach((e) => {
        if (e.number != 0) {
          this.productInfo.push(e);
        }
        // i++;
      });

      console.log(this.productInfo);
    },
  },
  created() {

    //获取登录的顾客的个人收获地址
    this.getAllAddress();
    // console.log(this.orderLines);

    this.filtersProductData();

    //时间
    this.formatDate();

  },
  computed: {
    //获取订单总价钱
    ...mapGetters("shopcart", ["total"]),
    ...mapState("shopcart", ["orderLines"]),
  },
};
</script>

<style lang="less">
.submitOrder {
  .header {
    top: 0;
  }
}
.address,
.ProductInfo,
.serviceTime {
  margin: 10px auto;
  box-shadow: 2px 2px 2px 2px #ece3ff;
  transition: 0.3s;
  width: 95%;
  border-radius: 5px;
}
.info {
  display: flex;
  flex-wrap: nowrap;
  span {
    font-size: 15px;
    flex: 1;
    label {
      color: #666;
    }
  }
}
.van-radio-group {
  .van-radio {
    padding: 10px 8px;
    width: 100%;
    border-bottom: 1px gray dotted;
    .AddressInfo {
      width: 100%;
    }
  }
}
.van-radio__label {
  display: inline-block;
  width: 100%;
}
.product {
  display: flex;
  span {
    flex: 1;
    font-size: 14px;
    label {
      color: #666;
    }
  }
}

.total {
  text-align: right;
  padding: 1vh 15vw 1vh 0;
}

.btnSubmit {
  width: 53%;
  height: 40px;
  background-image: linear-gradient(90deg, #7579ff, #bf73ff);
  text-align: center;
  color: #fff;
  border-radius: 22px;
  line-height: 40px;
  margin: 0 auto;
  margin-top: 2em;
  cursor: pointer;
}
.money {
  display: flex;
}
.money input {
  border: 0;
  font-size: 14px;
  line-height: 24px;
}
input::-webkit-input-placeholder {
  /* WebKit browsers */
  color: #999;
}
.money span {
  -webkit-box-flex: 0;
  -webkit-flex: none;
  flex: none;
  font-size: 14px;
  line-height: 24px;
  box-sizing: border-box;
  width: 6.2em;
  margin-right: 12px;
  color: #646566;
  text-align: center;
  word-wrap: break-word;
}

.submit {
  // width: 384px;
  height: 40px;
  line-height: 40px;
  margin: 16px;
  button {
    border-style: none;
    width: 100%;
    height: 100%;
    border-radius: 15px;
    background-color: red;
    color: white;
  }
}
</style>